package com.bbs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.bbs.po.Response;
import com.bbs.po.Topic;
import com.bbs.service.ResponseService;
import com.bbs.service.TopicService;

@Controller
public class responseController {
   
	@Autowired
	private ResponseService responseService;
	
	@Autowired
	private TopicService topicservice;
	
	@RequestMapping("/responselist")
	public ModelAndView responselist(@RequestParam(value="topicid" ,required =false ) Integer topicid,
			                     @RequestParam(value="pagenum" ,required =false ) Integer pagenum){
		ModelAndView mv = new ModelAndView("responselist");
		List<Response> list = new ArrayList<>();
		Topic topic = new Topic();
		topic = topicservice.getTopicById(topicid);
		int size = responseService.getResponseNum(topicid);
		
		if(pagenum < 1 || pagenum > (size/12)+1 || pagenum == null){
			list = responseService.getAllResponse(topicid,1,10);
		}
		else{
			list = responseService.getAllResponse(topicid,pagenum,10);
		}
		
		mv.addObject("topic",topic);
		mv.addObject("responselist", list);
		mv.addObject("topicid", topicid);
		mv.addObject("nextpage", pagenum+1);
		mv.addObject("lastpage", pagenum-1);
		return mv;
	}
	
	@RequestMapping("/newresponse")
	public ModelAndView newRresponse(HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		String topicid =  request.getParameter("topicid");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String author = (String) request.getSession().getAttribute("username");
		int id1 = Integer.parseInt(topicid);
		Response response = new Response();
		//Topic topic = new Topic();
		response.setContent(content);
		response.setTopicid(id1);
		response.setTitle(title);
		response.setAuthor(author);
		int s = responseService.saveResponse(response);
		if(s == 0){
			mv.setViewName("messagepage");
			mv.addObject("errorInfo", "�ظ�����ʧ��");
		}
		mv.setViewName("forward:/responselist?topicid="+id1+"&pagenum=1");
		return mv;
	}
}
